/**
 * Token数据访问层
 */

const Logger = require('../utils/logger')

class TokenRepository {
  constructor(db) {
    this.db = db
    this.collection = db.collection('user_tokens')
  }

  /**
   * 保存Token
   */
  async saveToken(tokenData) {
    try {
      const result = await this.collection.add({ data: tokenData })
      return result._id
    } catch (error) {
      Logger.error('TokenRepo', '保存Token失败', error)
      throw error
    }
  }

  /**
   * 查询Token
   */
  async findByToken(token) {
    try {
      const result = await this.collection.where({ token }).get()
      return result.data.length > 0 ? result.data[0] : null
    } catch (error) {
      Logger.error('TokenRepo', '查询Token失败', error)
      throw error
    }
  }

  /**
   * 删除用户的所有Token（退出登录）
   */
  async deleteByUserId(userId) {
    try {
      const result = await this.collection.where({ userId }).remove()
      return result.stats.removed
    } catch (error) {
      Logger.error('TokenRepo', '删除Token失败', error)
      throw error
    }
  }
}

module.exports = TokenRepository

